#include "toastlabel.h"
#include <QTimer>

namespace yc {

ToastLabel::ToastLabel(const QString& text, QWidget* parent) : QLabel(text, parent)
{
    setObjectName("toast");
}

void ToastLabel::showMessage(const QString& text, QWidget* parent, int timeout,
                             const QString& object_name)
{
    Q_ASSERT(parent);
    if (parent) {
        QRect r = parent->contentsRect();
        r.adjust(20, 20, -20, -20);
        ToastLabel* tl = new ToastLabel(text, parent);
        tl->setAttribute(Qt::WA_DeleteOnClose);
        tl->setWordWrap(true);
        if (!object_name.isEmpty()) {
            tl->setObjectName(object_name);
        }
        QFontMetrics fm = tl->fontMetrics();
        QRect br = fm.boundingRect(r, Qt::TextWordWrap, text.left(512));
        br.adjust(-20, -20, 20, 20); // + padding
        tl->resize(br.size());
        QPoint center = r.center();
        QPoint pos(center.x() - br.width() / 2, center.y() - br.height() / 2);
        tl->move(pos);
        tl->show();
        tl->raise();
        // auto closing
        QTimer::singleShot(timeout, tl, &ToastLabel::close);
    }
}

} // namespace yc
